﻿using CSASPNETBackgroundWorker;
using System;
using System.IO;
using System.Net;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.Linq;

namespace TestBackgroundWorker
{
    /*
     * 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestBackgroundWorker.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:ScriptManager ID="ScriptManager1"  runat="server"></asp:ScriptManager>
      <h2>Hello</h2>
      <asp:UpdatePanel ID="Panel1" runat="server">
        <ContentTemplate>
          <asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Enabled="False" Interval="500"></asp:Timer>
          <asp:Timer ID="InitTimer" runat="server" Interval="300"  Enabled="True" OnTick="InitTimer_Tick"></asp:Timer>
          <asp:Label ID="Progress" runat="server" Text="Loading..."></asp:Label>
          <asp:GridView ID="ExchangeRates" runat="server" OnPageIndexChanging="gridView_PageIndexChanging" AllowPaging="True"></asp:GridView>
        </ContentTemplate>
      </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

     */
    public partial class Default : System.Web.UI.Page
    {
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)Session["worker"];
            if (worker != null)
            {
                Progress.Text = "Loading " + worker.Progress + "%";
                Timer1.Enabled = worker.IsRunning;
                if (worker.Progress >= 100)
                {
                    LoadRatesFromDatabase();
                }
            }
        }
        protected void InitTimer_Tick(object sender, EventArgs e)
        {
            InitTimer.Enabled = false;
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new BackgroundWorker.DoWorkEventHandler(worker_DoWork);
            worker.RunWorker("http://www.nbp.pl/kursy/xml/LastA.xml");
            Session["worker"] = worker;
            Timer1.Enabled = true;
        }
        void worker_DoWork(ref int progress, ref object result, params object[] arguments)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(arguments[0].ToString());
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                SaveRates(response);
                progress = 50;
            }
            catch (Exception ex)
            {
                // TODO: Log problems
            }
            result = "Operation is completed.";
        }
        private void SaveRates(HttpWebResponse response)
        {
            using (Stream stream = response.GetResponseStream())
            {
                DataClassesDataContext context = new DataClassesDataContext();
                XDocument xDoc = XDocument.Load(stream);
                foreach (var result in xDoc.Descendants("pozycja"))
                {
                    KursyA record = new KursyA();
                    record.nazwa_waluty = result.Element("nazwa_waluty").Value;
                    record.przelicznik = int.Parse(result.Element("przelicznik").Value);
                    record.kod_waluty = result.Element("kod_waluty").Value;
                    record.kurs_sredni = result.Element("kurs_sredni").Value;
                    KursyA oldRecord = context.KursyAs.FirstOrDefault(x => x.kod_waluty == record.kod_waluty);
                    if (oldRecord != null)
                    {
                        if (oldRecord.kurs_sredni != record.kurs_sredni) oldRecord.kurs_sredni = record.kurs_sredni;
                        else if (oldRecord.nazwa_waluty != record.nazwa_waluty) oldRecord.nazwa_waluty = record.nazwa_waluty;
                        else if (oldRecord.przelicznik != record.przelicznik) oldRecord.przelicznik = record.przelicznik;
                        else continue;
                    }
                    else context.KursyAs.InsertOnSubmit(record);
                }
                context.SubmitChanges();
            }
            response.Close();
        }
        private void LoadRatesFromDatabase()
        {
            DataClassesDataContext context = new DataClassesDataContext();
            ExchangeRates.DataSource = context.GetTable<KursyA>();
            ExchangeRates.DataBind();
        }
        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ExchangeRates.PageIndex = e.NewPageIndex;
            LoadRatesFromDatabase();
        }
    }
}